package com.zw.yzk.kabu.view.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.adapter.GoodsDetailsImageAdapter;
import com.zw.yzk.kabu.adapter.header.HeaderHelper;
import com.zw.yzk.kabu.base.BaseActivity;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.data.network.task.AddShoppingCartTask;
import com.zw.yzk.kabu.im.IMUtils;
import com.zw.yzk.kabu.internal.component.DaggerGoodsDetailsComponent;
import com.zw.yzk.kabu.internal.module.ActivityModule;
import com.zw.yzk.kabu.internal.module.CollectGoodsModule;
import com.zw.yzk.kabu.internal.module.GoodsDetailsModule;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.management.ToolbarBuilder;
import com.zw.yzk.kabu.model.GoodsDetailsModel;
import com.zw.yzk.kabu.model.SubmitGoods;
import com.zw.yzk.kabu.model.SubmitOrder;
import com.zw.yzk.kabu.presenter.GoodsDetailsPresenter;
import com.zw.yzk.kabu.utils.CircleTransform;
import com.zw.yzk.kabu.utils.GlideImageLoader;
import com.zw.yzk.kabu.utils.ResUtils;
import com.zw.yzk.kabu.view.activity.imagedetails.ImageListDetailsActivity;
import com.zw.yzk.kabu.view.view.GoodsDetailsView;
import com.zw.yzk.kabu.view.widget.BuyGoodsDialog;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnClick;


/**
 * Created by zhanwei on 2017/2/6.
 */

public class GoodsDetailsActivity extends BaseActivity implements GoodsDetailsView {

    @Bind(R.id.details_list)
    RecyclerView detailsList;
    @Bind(R.id.buy_now)
    TextView buyNow;
    @Bind(R.id.add_shopping_cart)
    TextView addShoppingCart;
    @Bind(R.id.collect)
    CheckBox collect;
    private Banner banner;
    private TextView price;
    private TextView freight;
    private TextView goodsName;
    private ImageView sellerHead;
    private TextView sellerName;
    private TextView sellerIntroduction;
    private TextView shopIntroduction;
    private int shopOwnerId = -1;
    private TextView title;

    @Inject
    GoodsDetailsPresenter presenter;
    private GoodsDetailsModel goodsDetailsModel;
    private GoodsDetailsImageAdapter adapter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_goods_details;
    }

    @Override
    public void iniToolbar(BaseActivity activity) {
        View toolBar = ToolbarBuilder
                .createBuilder(this)
                .setTitle(getResources().getString(R.string.goods_details))
                .setRightImage(R.drawable.ic_shopping_cart)
                .build();
        title = (TextView) toolBar.findViewById(R.id.tool_bar_title);
    }

    @Override
    public void initComponent() {
        DaggerGoodsDetailsComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .goodsDetailsModule(new GoodsDetailsModule())
                .collectGoodsModule(new CollectGoodsModule())
                .build()
                .inject(this);
        presenter.setView(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initRecyclerView();
        getGoodsDetails(getIntent().getIntExtra(ActivityConstant.GOODS_DETAILS_ID, -1));
        LoadingDialogManager.getInstance().showLoadingDialog(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.destroy();
        }
    }

    @Override
    public void getGoodsDetailSuccess(GoodsDetailsModel model) {
        goodsDetailsModel = model;
        //设置标题
        if (title != null) {
            title.setText(model.getGoodsName());
        }
        //设置基本信息
        setBaseInfo(model);
        //设置轮播图列表
        setBanner(model.getBannerList());
        //设置图片列表
        setImageDetails(model.getIntroduceImageList());
        //设置收藏状态
        collect.setChecked(model.getIsCollected());
        collect.setText(model.getIsCollected() ? R.string.collected : R.string.uncollected);
        //设置店铺所有者id
        shopOwnerId = model.getShopOwnerId();
    }

    @Override
    public void getGoodsDetailFailed() {
        addShoppingCart.setBackgroundColor(Color.parseColor("#CCCCCC"));
        addShoppingCart.setEnabled(false);
        buyNow.setBackgroundColor(Color.parseColor("#CCCCCC"));
        buyNow.setEnabled(false);
    }

    @Override
    public void collectGoodsFailed() {
        collect.setChecked(!collect.isChecked());
        collect.setText(collect.isChecked() ? R.string.collected : R.string.uncollected);
    }

    @OnClick(R.id.right_image)
    public void enterShoppingCart() {
        startActivity(new Intent(this, ShoppingCartActivity.class));
    }

    @OnClick(R.id.store)
    public void enterStore() {
        Intent intent = new Intent(this, StoreActivity.class);
        intent.putExtra(ActivityConstant.STORE_OWNER_ID, shopOwnerId);
        startActivity(intent);
    }

    @OnClick(R.id.add_shopping_cart)
    public void addShoppingCart() {
        if (goodsDetailsModel == null) {
            return;
        }
        new BuyGoodsDialog.Builder(this, goodsDetailsModel.getGoodsId())
                .setImage(goodsDetailsModel.getCoverImage())
                .setPropertyList(goodsDetailsModel)
                .setConfirmClickedListener(new BuyGoodsDialog.OnConfirmClickedListener() {
                    @Override
                    public void onClick(int count, String skuId, float price, String property) {
                        AddShoppingCartTask.Goods goods = new AddShoppingCartTask.Goods();
                        goods.shopId = goodsDetailsModel.getShopId();
                        goods.productId = goodsDetailsModel.getGoodsId();
                        goods.count = count;
                        goods.skuId = skuId;
                        addShoppingCart(goods);

                        LoadingDialogManager.getInstance().showLoadingDialog(GoodsDetailsActivity.this);
                    }
                })
                .build()
                .showAtLocation(this.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
    }

    @OnClick(R.id.buy_now)
    public void buyNow() {
        if (goodsDetailsModel == null) {
            return;
        }
        new BuyGoodsDialog.Builder(this, goodsDetailsModel.getGoodsId())
                .setImage(goodsDetailsModel.getCoverImage())
                .setPropertyList(goodsDetailsModel)
                .setConfirmClickedListener(new BuyGoodsDialog.OnConfirmClickedListener() {
                    @Override
                    public void onClick(int count, String skuId, float price, String property) {
                        int receivedId;
                        try {
                            receivedId = DataBaseManager.getInstance().getLoginUser().getAddress().getReceiveId();
                        } catch (Exception e) {
                            //如果用户没有登录，那么传入0，在用户没有登录的情况下服务器首先会返回用户没有登录的错误
                            receivedId = 0;
                        }

                        ArrayList<SubmitOrder> orderList = new ArrayList<>();
                        ArrayList<SubmitGoods> goodsList = new ArrayList<>();

                        SubmitGoods goods = new SubmitGoods();
                        goods.setGoodsId(goodsDetailsModel.getGoodsId());
                        goods.setCount(count);
                        goods.setSkuId(skuId);
                        goods.setName(goodsDetailsModel.getGoodsName());
                        goods.setImage(goodsDetailsModel.getCoverImage());
                        goods.setPrice(price);
                        goods.setProperty(property);
                        goods.setFreight(goodsDetailsModel.getFreight());
                        goodsList.add(goods);

                        SubmitOrder order = new SubmitOrder();
                        order.setGoodsList(goodsList);
                        order.setShopId(goodsDetailsModel.getShopId());
                        order.setReceiverInfoId(receivedId);
                        order.setShopName(goodsDetailsModel.getShopName());
                        orderList.add(order);

                        Intent intent = new Intent(GoodsDetailsActivity.this, ConfirmGoodsOrderActivity.class);
                        intent.putParcelableArrayListExtra(ActivityConstant.CONFIRM_GOODS_ORDER_LIST, orderList);
                        startActivity(intent);
                    }
                })
                .build()
                .showAtLocation(this.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
    }

    @OnClick(R.id.layout_collect)
    public void setCollectStatus() {
        if (goodsDetailsModel == null) {
            return;
        }
        if (collect.isChecked()) {
            collect.setChecked(false);
            collect.setText(R.string.uncollected);
        } else {
            collect.setChecked(true);
            collect.setText(R.string.collected);
        }
        collectGoods(collect.isChecked());
    }

    @OnClick(R.id.chat)
    public void startCharPage() {
        User user = DataBaseManager.getInstance().getLoginUser();
        if(user == null || !user.isLogin()) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        if(shopOwnerId != -1) {
            IMUtils.startPrivateConversationActivity(this, String.valueOf(shopOwnerId), sellerName.getText().toString());
        }
    }

    /**
     * 初始化recyclerView
     */
    private void initRecyclerView() {
        detailsList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new GoodsDetailsImageAdapter(null);
        View header = LayoutInflater.from(this).inflate(R.layout.recycler_header_goods_details, detailsList, false);
        View ownerInfoLayout = header.findViewById(R.id.layout_owner_info);
        banner = (Banner) header.findViewById(R.id.banner);
//        banner.setCustomIndicator((PageIndicator) banner.findViewById(R.id.indicator_circle));
        price = (TextView) header.findViewById(R.id.price);
        freight = (TextView) header.findViewById(R.id.freight);
        goodsName = (TextView) header.findViewById(R.id.goods_name);
        sellerHead = (ImageView) header.findViewById(R.id.seller_head);
        sellerName = (TextView) header.findViewById(R.id.seller_name);
        sellerIntroduction = (TextView) header.findViewById(R.id.seller_introduction);
        shopIntroduction = (TextView) header.findViewById(R.id.shop_introduction);

        ownerInfoLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GoodsDetailsActivity.this, HomePageActivity.class);
                intent.putExtra(ActivityConstant.HOME_PAGE_ID, shopOwnerId);
                startActivity(intent);
            }
        });
        //给RecyclerView添加头部
        HeaderHelper.createHelper(adapter).addHeader(detailsList, header);
    }

    /**
     * 设置商品详情
     *
     * @param model 商品信息
     */
    private void setBaseInfo(GoodsDetailsModel model) {
        if (!model.getIsBuyable()) {
            buyNow.setBackgroundColor(Color.parseColor("#CCCCCC"));
            buyNow.setEnabled(false);
        }

        if (!model.getSkuList().isEmpty()) {
            price.setText(ResUtils.formatCurrency(this, model.getSkuList().get(0).getPrice()));
        }
        String freightStr = getResources().getString(R.string.freight) + ": "
                + ResUtils.formatCurrency(this, model.getFreight());
        freight.setText(freightStr);

        goodsName.setText(model.getGoodsName());
        sellerName.setText(model.getShopOwner());
        sellerIntroduction.setText(model.getShopOwnerSign());
        shopIntroduction.setText(model.getIntroduce());
        if (TextUtils.isEmpty(model.getIntroduce())) {
            shopIntroduction.setVisibility(View.GONE);
        }
        Glide.with(this)
                .load(model.getShopOwnerHead())
                .transform(new CircleTransform(this))
                .error(R.drawable.ic_default_head)
                .into(sellerHead);
    }

    /**
     * 设置轮播图
     *
     * @param list 轮播图列表
     */
    public void setBanner(List<GoodsDetailsModel.Banner> list) {
        final ArrayList<String> imageList = new ArrayList<>();
        for (GoodsDetailsModel.Banner banner : list) {
            imageList.add(banner.getImage());
        }
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(imageList);
        //设置轮播时间
        banner.setDelayTime(1500);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Rect rect = new Rect();
                banner.getGlobalVisibleRect(rect);
                ImageListDetailsActivity.startImageListActivity(GoodsDetailsActivity.this, imageList, imageList.get(position), rect);
            }
        });
        banner.start();
    }

    /**
     * 设置图片详情
     *
     * @param list 图片列表
     */
    private void setImageDetails(List<GoodsDetailsModel.IntroduceImage> list) {
        adapter.refresh(list);
    }

    /**
     * 获取商品详情
     *
     * @param goodsId 商品id
     */
    private void getGoodsDetails(int goodsId) {
        presenter.getGoodsDetails(goodsId);
    }

    /**
     * 添加购物车
     *
     * @param goods 商品信息
     */
    private void addShoppingCart(AddShoppingCartTask.Goods goods) {
        presenter.addShoppingCart(goods);
    }

    /**
     * 收藏或者取消收藏商品
     *
     * @param collect 是否收藏
     */
    public void collectGoods(boolean collect) {
        presenter.collectGoods(goodsDetailsModel.getGoodsId(), collect);
    }

}
